<?php

$db = new Database();
$auth = Auth::getAuth('current_user');

$formID = $_POST['FormID'];
$insert_result = $_POST['ID'];
$workflow_id = $_POST['Workflow_ID'];
$node_id = $_POST['Node_ID'];
$mode = $_POST['Mode'];
$keywordsField = json_decode($_POST['KeywordsField'], true);


$myRequest = new Request();
$myRequest->load($formID, $insert_result);

$fields = array();
$fieldResults = $myRequest->fields;

$date = $this->currentDateTime();
$fieldEnabled = json_decode($_POST['fieldEnabled'], true);
$computedFields = json_decode($_POST['computedFields'], true);
$reservedFields = array("TrackNo", "Requestor", "Status", "Processor", "LastAction", "DateCreated", "DateUpdated", "CreatedBy", "UpdatedBy", "Unread", "Node_ID", "Workflow_ID"
    , "fieldEnabled", "fieldRequired", "fieldHiddenValues", "imported", "Repeater_Data");

if ($mode == 'formApproval') {
    foreach ($fieldResults as $field) {
        $index_search = in_array($field['COLUMN_NAME'], $fieldEnabled);
        $reserved_index = in_array($field['COLUMN_NAME'], $reservedFields);
        $computed_index = in_array($field['COLUMN_NAME'], $computedFields);

		$fields["middleware_process"] = 0;
        if ($index_search || $reserved_index || $computed_index) {
            if (is_array($_POST[$field['COLUMN_NAME']])) {
                $fields[$field['COLUMN_NAME']] = join("|^|", $_POST[$field['COLUMN_NAME']]);
            } else if ($field['COLUMN_NAME'] == 'DateCreated' && $insert_result == '0') {
                $fields[$field['COLUMN_NAME']] = $date;
            } else if ($field['COLUMN_NAME'] == 'DateUpdated') {
                $fields[$field['COLUMN_NAME']] = $date;
            
			} else {
				if($field['COLUMN_NAME'] == 'TrackNo'){
					$myRequest->trackNo = $_POST[$field['COLUMN_NAME']];
				}
                $fields[$field['COLUMN_NAME']] = $_POST[$field['COLUMN_NAME']];
            }
        }
    }
}
if ($mode == 'viewApproval') {
    $fields['Node_ID'] = $node_id;
    $fields['Workflow_ID'] = $workflow_id;
}

if ($insert_result == '0') {
    $myRequest->data = $fields;
	
	$myRequest->save();
} else {
    if ($node_id == 'Cancel') {
        $fields['Status'] = 'Cancelled';
        $fields['Processor'] = '';
        $fields['LastAction'] = '';
    }

    if ($node_id == 'Save' || $node_id == 'Cancel') {
        $logDoc = new Request_Log($db);
        $logDoc->form = new Form($db, $formID);
        $logDoc->request_id = $insert_result;

        if ($node_id == 'Save') {
            $logDoc->details = 'Saved';
        } else {
            $logDoc->details = 'Cancelled';
        }

        $logDoc->created_by = new Person($db, $auth['id']);
        $logDoc->date_created = $date;
        $logDoc->save();
    }
    $myRequest->data = $fields;
    $myRequest->createFieldLevelLogs($fieldEnabled);
    $myRequest->modify();
}


if ($node_id != 'Save' && $node_id != 'Cancel') {
    $myRequest->keywordFields = $keywordsField;
    $myRequest->processWF();
}
if ($mode == 'formApproval') {
	//var_dump($myRequest);
    /* ========== Move Attachment Files ========== */
    $files = $_POST['attachment_files'];

    $filename = explode(",", $files);

    // Create folder for the postImage
    $path = "images/attachment";
    $to = "images/attachment/temporaray_files/";
    $trackNo = $myRequest->trackNo;
    upload::move_attach_files($trackNo, $path, $auth, $filename, $to);
//    header('location:/application?id=' . functions::base_encode_decode("encrypt", $formID));
    // if($auth['user_level_id']=="2"){
    //     $myRequest->responseData['headerLocation'] = "/application?id=" . functions::base_encode_decode("encrypt", $formID);
    // }else{
    //     $myRequest->responseData['headerLocation'] = "/user_view/application?id=" . functions::base_encode_decode("encrypt", $formID);   
    // }
    $myRequest->responseData['headerLocation'] = "/application?id=" . functions::base_encode_decode("encrypt", $formID);
    $myRequest->responseData['formId'] = $myRequest->formId;
    
    print_r(json_encode($myRequest->responseData));
    
}
if ($mode == 'viewApproval') {
    echo 'Request has been processed';
}
?>
